package jwt

import (
	"errors"
	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"net/http"

	"go-gin-example/pkg/e"
	"go-gin-example/pkg/util"
)

func JWT() gin.HandlerFunc {
	return func(c *gin.Context) {
		var code int
		var data interface{}

		code = e.SUCCESS
		token := c.Query("token")
		if token == "" {
			code = e.ErrorNotExistToken
		} else {
			claims, err := util.ParseToken(token)
			zap.L().Info("获取claims的值", zap.Any("claims", claims))
			if err != nil {
				// 判断错误类型
				var validationError *jwt.ValidationError
				if errors.As(err, &validationError) {
					if validationError.Errors&jwt.ValidationErrorExpired != 0 {
						// Token 过期
						code = e.ErrorAuthCheckTokenTimeout
					} else {
						// Token 非法
						code = e.ErrorValidToken
					}
				}
			}
		}

		if code != e.SUCCESS {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code": code,
				"msg":  e.GetMsg(code),
				"data": data,
			})

			c.Abort()
			return
		}

		c.Next()
	}
}
